#include "http_server.hpp"
#define WWWROOT "./wwwroot/"

std::string RequestStr(const Http::HttpRequest & req)
{
    std::stringstream ss;
    ss<<req._method<<" "<<req._path<<" "<<req._version<<"\r\n";
    for(auto & it:req._params)
    {
        ss<<it.first<<": "<<it.second<<"\r\n";
    }
    for(auto & it:req._headers)
    {
        ss<<it.first<<": "<<it.second<<"\r\n";
    }
    ss<<"\r\n";
    ss<<req._body;
    return ss.str();
}

void Hello(const Http::HttpRequest & req,Http::HttpResponse * rsp)
{
    rsp->SetContent(RequestStr(req),"text/plain");
    // sleep(15);
}

void Login(const Http::HttpRequest & req,Http::HttpResponse * rsp)
{
    rsp->SetContent(RequestStr(req),"text/plain");
}

void PutFile(const Http::HttpRequest &req, Http::HttpResponse *rsp) 
{
    std::string pathname = WWWROOT + req._path;
    Http::Util::WriteFile(pathname, req._body);
}

void DelFile(const Http::HttpRequest & req,Http::HttpResponse * rsp)
{
    rsp->SetContent(RequestStr(req),"text/plain");
}

int main()
{
    Http::HttpServer server(8080);
    server.SetThreadCount(3);//线程数
    server.SetBaseDir(WWWROOT);//相对根目录
    server.Get("/hello",Hello);//get路由
    server.Post("/login",Login);//post路由
    server.Put("/1234.txt",PutFile);//put路由
    server.Delete("/1234.txt",DelFile);//delete路由
    server.Listen();
    return 0;
}